package jehc.djshi.common.base;

import jehc.djshi.common.cache.redis.RedisUtil;
import jehc.djshi.common.constant.CacheConstant;
import jehc.djshi.common.constant.SessionConstant;
import jehc.djshi.common.entity.*;
import jehc.djshi.common.session.HttpSessionUtils;
import jehc.djshi.common.util.ExceptionUtil;
import jehc.djshi.common.util.JsonUtil;
import jehc.djshi.common.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
 * @Desc CommonUtils
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
public class CommonUtils {

    @Autowired
    RedisUtil redisUtil;

    /**
     * 根据KEY获取平台常量
     * @param key
     * @return
     */
    public ConstantEntity getXtConstantCache(String key) {
        String data = ""+redisUtil.hget(CacheConstant.SYSHASH,CacheConstant.XTCONSTANTCACHE);
        List<ConstantEntity> xtConstantList = JsonUtil.toFList(data,ConstantEntity.class);
        for (int i = 0; i < xtConstantList.size(); i++) {
            ConstantEntity xtConstant = xtConstantList.get(i);
            if (key.equals(xtConstant.getCkey())) {
                return xtConstant;
            }
        }
        return null;
    }

    /**
     * 根据key获取行政区域集合
     * @param key
     * @return
     */
    public List<AreaRegionEntity> getXtAreaRegionCache(String key) {
        String data = ""+redisUtil.hget(CacheConstant.SYSHASH,CacheConstant.XTAREAREGIONCACHE);
        List<AreaRegionEntity> list = JsonUtil.toFList(data,AreaRegionEntity.class);
        List<AreaRegionEntity> arList = new ArrayList<AreaRegionEntity>();
        if(StringUtil.isEmpty(key)){
            for (int i = 0; i < list.size(); i++) {
                AreaRegionEntity xtAreaRegion = list.get(i);
                if (xtAreaRegion.getPARENT_ID() ==  1) {
                    arList.add(xtAreaRegion);
                }
            }
        }else{
            for (int i = 0; i < list.size(); i++) {
                AreaRegionEntity xtAreaRegion = list.get(i);
                if (key.equals(""+xtAreaRegion.getPARENT_ID())) {
                    arList.add(xtAreaRegion);
                }
            }
        }
        return arList;
    }

    /**
     * 根据KEY获取平台字典
     * @param key
     * @return
     */
    public List<DataDictionaryEntity> getXtDataDictionaryCache(String key) {
        String data = ""+redisUtil.hget(CacheConstant.SYSHASH,CacheConstant.XTDATADICTIONARYCACHE);
        List<DataDictionaryEntity> xtDataDictionaryList = JsonUtil.toFList(data,DataDictionaryEntity.class);
        List<DataDictionaryEntity> list = new ArrayList<DataDictionaryEntity>();
        String id ="";
        for (int i = 0; i < xtDataDictionaryList.size(); i++) {
            DataDictionaryEntity xtDataDictionary = xtDataDictionaryList.get(i);
            if(key.equals(xtDataDictionary.getXt_data_dictionary_value())){
                id = xtDataDictionary.getXt_data_dictionary_id();
                break;
            }
        }
        for (int i = 0; i < xtDataDictionaryList.size(); i++) {
            DataDictionaryEntity xtDataDictionary = xtDataDictionaryList.get(i);
            if (id.equals(xtDataDictionary.getXt_data_dictionary_pid()) && !"".equals(id)) {
                list.add(xtDataDictionary);
            }
        }
        return list;
    }

    /**
     * 判断IP是否为黑户
     * @param ip
     * @return
     */
    public boolean getXtIpFrozenCache(String ip){
        String data = ""+redisUtil.hget(CacheConstant.SYSHASH,CacheConstant.XTIPFROZENCACHE);
        List<IpFrozenEntity> xtIpFrozenList = JsonUtil.toFList(data,IpFrozenEntity.class);
        for (int i = 0; i < xtIpFrozenList.size(); i++) {
            IpFrozenEntity xtIpFrozen = xtIpFrozenList.get(i);
            if(ip.equals(xtIpFrozen.getXt_ip_frozen_address())){
                return false;
            }
        }
        return true;
    }

    /**
     * 获取公共功能缓存
     * @return
     */
    public String getXtFunctioninfoCommonCache(){
        String data = ""+redisUtil.hget(CacheConstant.SYSHASH,CacheConstant.XTFUNCTIONINFOCOMMONCACHE);
        return data;
    }

    /**
     * 根据KEY获取平台路径
     *
     * @param key
     * @return
     */
    public List<PathEntity> getXtPathCache(String key) {
        String data = ""+redisUtil.hget(CacheConstant.SYSHASH,CacheConstant.XTPATHCACHE);
        List<PathEntity> pathEntities = JsonUtil.toFList(data,PathEntity.class);
        if(null != pathEntities && !pathEntities.isEmpty()){
            List<PathEntity> list = new ArrayList<PathEntity>();
            for (int i = 0; i < pathEntities.size(); i++) {
                PathEntity pathEntity = pathEntities.get(i);
                if (key.equals(pathEntity.getXt_value())) {
                    list.add(pathEntity);
                }
            }
            return list;
        }
        return null;
    }







    ////////////////////////Token工具方法独立处理中心////////////////
    @Autowired
    HttpSessionUtils httpSessionUtils;

    /**
     * 读取 TOKEN
     * @param request
     * @return
     */
    public static final String getTokenId(HttpServletRequest request) {
        HttpHeaders headers = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            headers.add(key, value);
        }
        String token = request.getHeader(SessionConstant.TOKEN);
        return token;
    }

    /**
     * 获取token信息
     * @param request
     * @return
     */
    public String getTokenInfo(HttpServletRequest request){
        String token = getTokenId(request);
        if(StringUtils.isEmpty(token)){
            return null;
        }
        return getTokenInfo(token);
    }

    public BaseHttpSessionEntity getBaseHttpSessionEntity() {
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
            String baseHttpSessionEntityJson = getTokenInfo(request);
            if(StringUtils.isEmpty(baseHttpSessionEntityJson)){
                return null;
            }
            BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(baseHttpSessionEntityJson, BaseHttpSessionEntity.class);
            return baseHttpSessionEntity;
        } catch (Exception e) {
            throw new ExceptionUtil(e.getMessage(),e.getCause());
        }
    }

    /**
     * 获取tokeninfo信息
     * @param token
     * @return
     */
    public String getTokenInfo(String token) {
        return httpSessionUtils.getAttribute(SessionConstant.TOKEN_STORE_PATH+token);
    }

    /**
     * 当前用户
     * @return
     */
    public OauthAccountEntity account() {
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
            String baseHttpSessionEntityJson = getTokenInfo(request);
            if(StringUtils.isEmpty(baseHttpSessionEntityJson)){
                return null;
            }
            BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(baseHttpSessionEntityJson, BaseHttpSessionEntity.class);
            if(null != baseHttpSessionEntity){
                return baseHttpSessionEntity.getOauthAccountEntity();
            }
        } catch (Exception e) {
            throw new ExceptionUtil(e.getMessage(),e.getCause());
        }
        return null;
    }

    /**
     * 当前当前账号编号
     * @param request
     * @return
     */
    public String getAccountId(HttpServletRequest request) {
        try {
            String baseHttpSessionEntityJson = getTokenInfo(request);
            if(StringUtils.isEmpty(baseHttpSessionEntityJson)){
                return null;
            }
            BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(baseHttpSessionEntityJson, BaseHttpSessionEntity.class);
            if(null != baseHttpSessionEntity){
                OauthAccountEntity oauthAccountEntity = baseHttpSessionEntity.getOauthAccountEntity();
                if(null != oauthAccountEntity){
                    return oauthAccountEntity.getAccount_id();
                }
            }
        } catch (Exception e) {
            throw new ExceptionUtil(e.getMessage(),e.getCause());
        }
        return null;
    }

    /**
     * 当前用户名称
     * @param request
     * @return
     */
    public String getUname(HttpServletRequest request) {
        try {
            String baseHttpSessionEntityJson = getTokenInfo(request);
            if(StringUtils.isEmpty(baseHttpSessionEntityJson)){
                return null;
            }
            BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(baseHttpSessionEntityJson, BaseHttpSessionEntity.class);
            if(null != baseHttpSessionEntity){
                OauthAccountEntity oauthAccountEntity = baseHttpSessionEntity.getOauthAccountEntity();
                if (null != oauthAccountEntity) {
                    return oauthAccountEntity.getName();
                }
            }
        } catch (Exception e) {
            throw new ExceptionUtil(e.getMessage(),e.getCause());
        }
        return null;
    }

    /**
     * 获取当前用户的数据权限
     * @return
     */
    public List<String> systemUandM(){
        try {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
            String baseHttpSessionEntityJson = getTokenInfo(request);
            if(StringUtils.isEmpty(baseHttpSessionEntityJson)){
                return null;
            }
            BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(baseHttpSessionEntityJson, BaseHttpSessionEntity.class);
            if(null != baseHttpSessionEntity){
                return baseHttpSessionEntity.getSystemAM();
            }
        } catch (Exception e) {
            throw new ExceptionUtil("获取systemUandM出现异常："+e.getMessage());
        }
        return null;
    }

    /**
     * 判断当前用户是否为超级管理员
     * @return
     */
    public boolean isAdmin() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
        String baseHttpSessionEntityJson = getTokenInfo(request);
        if(StringUtils.isEmpty(baseHttpSessionEntityJson)){
            return false;
        }
        BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(baseHttpSessionEntityJson, BaseHttpSessionEntity.class);
        if(null != baseHttpSessionEntity){
            OauthAccountEntity oauthAccountEntity = baseHttpSessionEntity.getOauthAccountEntity();
            List<OauthAdminSysEntity> oauthAdminSysEntities = JsonUtil.toFList(baseHttpSessionEntity.getOauthAdminSysEntities(), OauthAdminSysEntity.class);
            if (null != oauthAccountEntity && null != oauthAdminSysEntities && !oauthAdminSysEntities.isEmpty()) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
}
